package com.douyuehan.doubao.project.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.douyuehan.doubao.project.mapper.BmsTagMapper;
import com.douyuehan.doubao.project.mapper.BmsTopicMapper;
import com.douyuehan.doubao.project.mapper.BmsUserMapper;
import com.douyuehan.doubao.project.model.dto.CreateTopicDTO;
import com.douyuehan.doubao.project.model.entity.BmsPost;
import com.douyuehan.doubao.project.model.entity.BmsTag;
import com.douyuehan.doubao.project.model.entity.BmsTopicTag;
import com.douyuehan.doubao.project.model.entity.BmsUser;
import com.douyuehan.doubao.project.model.vo.PostVO;
import com.douyuehan.doubao.project.model.vo.ProfileVO;
import com.douyuehan.doubao.project.service.BmsPostService;
import com.douyuehan.doubao.project.service.BmsTagService;
import com.douyuehan.doubao.project.service.BmsTopicTagService;
import com.douyuehan.doubao.project.service.BmsUserService;
import com.vdurmont.emoji.EmojiParser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;


@Service
public class BmsPostServiceImpl extends ServiceImpl<BmsTopicMapper, BmsPost> implements BmsPostService {

    @Resource
    private BmsTagMapper bmsTagMapper;

    @Autowired
    private BmsTopicTagService bmsTopicTagService;

    @Resource
    private BmsUserMapper bmsUserMapper;

    @Autowired
    @Lazy//解决你业务层调用我,我业务层调用你的循环调用问题
    private BmsTagService bmsTagService;

    @Autowired
    private BmsUserService bmsUserService;


    @Override
    public Page<PostVO> getList(Page<PostVO> page, String tab) {
        // 查询所有帖子
        Page<PostVO> iPage = this.baseMapper.selectListAndPage(page, tab);
        // 对每一个帖子进行处理
        iPage.getRecords().forEach(topic -> {
            //根据帖子id获取【帖子标签关联表】（多对多关系，A表B表A-B表设计）
            List<BmsTopicTag> topicTags = bmsTopicTagService.selectByTopicId(topic.getId());
            if (!topicTags.isEmpty()) {
                List<String> tagIds = topicTags.stream().map(BmsTopicTag::getTagId).collect(Collectors.toList());//根据帖子id获取标签id
                List<BmsTag> tags = bmsTagMapper.selectBatchIds(tagIds);//根据标签id获取【标签表】信息
                topic.setTags(tags);
            }
        });
        return iPage;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public BmsPost create(CreateTopicDTO dto, BmsUser user) {
        BmsPost topic1 = this.baseMapper.selectOne(new LambdaQueryWrapper<BmsPost>().eq(BmsPost::getTitle, dto.getTitle()));
        Assert.isNull(topic1, "话题已存在，请修改");

        // 帖子插【帖子表】
        BmsPost topic = BmsPost.builder()
                .userId(user.getId())
                .title(dto.getTitle())
                .content(EmojiParser.parseToAliases(dto.getContent()))
                .createTime(new Date())
                .build();
        this.baseMapper.insert(topic);

        // 【用户表】该用户积分增加
        int newScore = user.getScore() + 1;
        bmsUserMapper.updateById(user.setScore(newScore));

        // 标签
        if (!ObjectUtils.isEmpty(dto.getTags())) {
            // 把标签依次保存到【标签表】
            List<BmsTag> tags = bmsTagService.insertTags(dto.getTags());
            // 在【帖子标签关系表】处理标签id与话题id的关联
            bmsTopicTagService.createTopicTag(topic.getId(), tags);
        }

        return topic;
    }

    @Override
    public Map<String, Object> viewTopic(String id) {
        Map<String, Object> map = new HashMap<>(16);
        //将【贴子内容存放map集合】
        BmsPost topic = this.baseMapper.selectById(id);//根据帖子id获取帖子内容
        Assert.notNull(topic, "当前话题不存在,或已被作者删除");

        topic.setView(topic.getView() + 1);// 更新帖子查看次数
        this.baseMapper.updateById(topic);

        topic.setContent(EmojiParser.parseToUnicode(topic.getContent()));// emoji转码
        map.put("topic", topic);

        //将【标签存入map集合】
        QueryWrapper<BmsTopicTag> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(BmsTopicTag::getTopicId, topic.getId());//从【帖子标签关系表】中过滤出帖子id对应的对象
        Set<String> set = new HashSet<>();
        for (BmsTopicTag articleTag : bmsTopicTagService.list(wrapper)) {
            set.add(articleTag.getTagId());
        }
        List<BmsTag> tags = bmsTagService.listByIds(set);
        map.put("tags", tags);

        //将【用户信息存入map集合】
        ProfileVO user = bmsUserService.getUserProfile(topic.getUserId());// 作者
        map.put("user", user);

        return map;
    }
}
